const {
    createHash
} = require('crypto');
const { generateToken, generateUniqueKey, } = require('../utils/token');
const { readUserData, writeUserData, } = require('../file');
const { userResponseWrapper, } = require('../result');
const { dealPostData, } = require('../formatData');
const md5 = require('md5');

const dealPostRequest = (pathname, request, response) => {
    console.log("pathname::", pathname);
    const requestMap = {
        "/api/login": async() => {
            const { data } = await dealPostData(request);
            console.log("login data::", data);
            // 读取用户信息
            const userList = await readUserData();
            // 检测用户是否为本系统的注册用户
            const registered = () => {
                return (userList || []).some(
                    user => user?.userPhone === data?.userPhone
                    && user?.userPassword === data?.userPassword
                    && user?.userName === data?.userName
                )
            };
            console.log("数据::", data, registered());
            // 此处应该使用算法进行加快查找
            if(registered()) {
                // 用户已经是本系统注册用户，只是 token 失效了，重新生成并颁发新的 token
                const uniqueKey = generateUniqueKey(data);
                for (let i = 0; i < userList.length; i++) {
                    const user = userList[i];
                    if(user?.userPhone === data?.userPhone 
                        && user?.userPassword === data?.userPassword
                        && user?.userName === data?.userName
                    ) {
                        user.key = uniqueKey;
                        break;
                    }
                }
                await writeUserData(JSON.stringify(userList));
                const jwt = generateToken({
                    userKey: uniqueKey,
                    expires: 60 * 60,
                });
                response.write(userResponseWrapper(JSON.stringify({
                    loginStatus: false,
                    registered: true,
                    token: jwt,
                })));
            }else {
                // 如果没有找到，说明该用户是未注册用户
                response.write(userResponseWrapper(JSON.stringify({
                    loginStatus: false,
                    registered: false,
                })));
            }
            response.end();
            console.log("userList::", userList);
        },
    };
    requestMap[pathname]();
};

module.exports = dealPostRequest;